package com.dong.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @author dongjian
 * <p>
 * order值越小优先级越高
 * 如果order值是相同的，那么过滤器的优先级：defaultFilter > 路由过滤器 > GlobalFilter
 */
@Order(-1)
@Component
public class AuthorizedFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        // 2.获取参数中的authorization参数
        String authorization = params.getFirst("authorization");
        // 3.判断参数的用户名是否符合条件
        // 4.如果是admin则放行
        if (Objects.equals(authorization, "admin")) {
            return chain.filter(exchange);
        }
        // 5.如果不满足条件则拦截
        // 5.1设置状态码 401:未登录
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        // 5.2拦截请求
        return exchange.getResponse().setComplete();
    }

    /**
     * 等同于 @order(-1) 注解
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
